package 富婆梦.第一阶段.Java基础视频学习.线程的练习.作业1;

/**
 * @ProjectName: java-learning
 * @Package: 富婆梦.第一阶段.线程的练习
 * @ClassName: RyanAndMonicaJob
 * @Author: hemengjin
 * @Description:
 * @Date:2021/10/17 22:43
 * @Version: 1.0
 */
public class RyanAndMonicaJob implements Runnable {
    private BankAccount account = new BankAccount();

    private synchronized void makeWithdrawal(int amount) {
        if (account.getBalance() >= amount) {
            System.out.println(Thread.currentThread().getName()+" is about to withdraw");
            try {
                Thread.sleep(500);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" work up");
            account.withdraw(amount);
            System.out.println(Thread.currentThread().getName()+" finish the withdraw,there have "+account.getBalance());
        }else {
            System.out.println("Sorry,ont enough for"+Thread.currentThread().getName());
        }
    }

    @Override
    public void run() {
        for (int i=0;i<10;i++){
            if (account.getBalance()<0){
                System.out.println("Overdrawn");
            }
            makeWithdrawal(10);
        }
    }

    public static void main(String[] args) {
        RyanAndMonicaJob theJob = new RyanAndMonicaJob();
        Thread one = new Thread(theJob);
        Thread two = new Thread(theJob);
        one.setName("Ryan");
        two.setName("Monica");
        one.start();
        two.start();
    }
}
